import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:secverify_plugin/secverify.dart';
import 'package:sharesdk_plugin/sharesdk_defines.dart';
import 'package:sharesdk_plugin/sharesdk_interface.dart';
import 'package:sharesdk_plugin/sharesdk_register.dart';
import 'package:sph_driver/AppConfig/Config.dart';
import 'package:sph_driver/Login/MobLogin.dart';
import 'dart:io';


import '../AppConfig/CustomButton.dart';
import '../AppConfig/RouteAct.dart';
import '../Main/CustomerService/VerifyPhoneUserID.dart';
import '../Main/ProtocolDisplay.dart';
import '../Tabbar/TabbarView.dart';
import '../http/api.dart';
import '../http/getapi.dart';
import '../l10n/messages.dart';
import 'ChooseCountryList.dart';
import 'SMSView.dart';


class LoginVC extends StatefulWidget {
  const LoginVC({super.key, required this.backType});
  final int backType;
  @override
  State<LoginVC> createState() => _LoginVCState();
}

class _LoginVCState extends State<LoginVC> {
  DateTime? lastPressed;
  @override
  Widget build(BuildContext context) {

    var messages = AppLocalizations.of(context)!;
    return WillPopScope(

        onWillPop: () async {
          final now = DateTime.now();
          // 如果 lastPressed 为空或者间隔时间超过 2 秒，则更新 lastPressed 并提示用户
          if (lastPressed == null || now.difference(lastPressed!) > Duration(seconds: 2)) {
            lastPressed = now;
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text('再按一次退出'),
                duration: Duration(seconds: 2),
              ),
            );
            return false; // 不退出
          }
          return true; // 退出应用

        },
        child:
        Scaffold(
            backgroundColor: Colors.white,
            appBar: AppBar(
              backgroundColor: Colors.white10,
              elevation: 0,
            leading: widget.backType==1?null:IconButton(

              onPressed: (){
                Navigator.of(context).pushAndRemoveUntil(
                    MaterialPageRoute(builder: (builder) {
                      return TabbarView(pateIndex: 0,);
                    }), (route) => route == null);
              },
              icon: Icon(Icons.arrow_back_ios,size: 20.w,color: MyColors.textColor,),
            ),
            ),
            body: ListView(
              children: [
                SizedBox(height: 36.h),
                Container(
                  margin: EdgeInsets.only(left: 30.h),
                  alignment: Alignment.centerLeft,
                  height: 60.h,
                  width: 181.w,

                  child:Image.asset("lib/Images/login/欢迎使用速配货司机版@3x.png"),
                ),
                SizedBox(height: 36.h),
                MobileSms(),


              ],
            )
        )
    );
  }
}





class MobileSms extends StatefulWidget {
  const MobileSms({super.key});

  @override
  State<MobileSms> createState() => _MobileSmsState();
}

class _MobileSmsState extends State<MobileSms> {
  int count = 0;
  String phoneNum = "";
  String smsCode = "";
  String CountryNum = "+86";
  String isAgree = "0";
  String verificationResult = '';

  bool _isButtonEnabled = true;
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      // 在页面加载后调用 showDialog
      // _showDialog();
    });
  }

  void _showDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return BrnDialog(
          titleText: '欢迎使用速配货',
          messageText:'我们将收集您提交的【身份证】信息，用于道路运输个人资料安全合规补全；如果您不同意该项授权，我们将不会获取您提交的个人信息，并且当前功能将无法正常使用',
          actionsWidget: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(); // 关闭对话框
              },
              child: Text("不同意",style: TextStyle(color: Colors.black),),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(); // 关闭对话框
              },
              child: Text("同意",style: TextStyle(color: MyColors.themeColor),),
            ),
          ],
        );
      },
    );
  }
  DateTime? lastPressed;
  @override
  Widget build(BuildContext context) {
    var messages = AppLocalizations.of(context)!;
    final screenSize = MediaQuery.of(context).size;
    return WillPopScope(
        onWillPop: () async {
          print("再按一次退出");
          // 获取当前时间
          final now = DateTime.now();
          // 如果 lastPressed 为空或者间隔时间超过 2 秒，则更新 lastPressed 并提示用户
          if (lastPressed == null || now.difference(lastPressed!) > Duration(seconds: 2)) {
            lastPressed = now;
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text('再按一次退出'),
                duration: Duration(seconds: 2),
              ),
            );
            return false; // 不退出
          }
          return true; // 退出应用
    },
    child:
      Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          height: 40.h,
          width: 300.w,
          margin: EdgeInsets.only(left: 30.w,right: 30.w),
          alignment: Alignment.centerLeft,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(30),
            color: Color.fromRGBO(248, 248, 248, 1),
          ),
          child: Row(
            children: [
              TextButton(onPressed: ()async{
                final result=await Navigator.push( context, FadeRoute(page:ChooseCountryList()));

                if(result!=null){
                  setState(() {
                    CountryNum=result;
                  });

                }
              }, child: Text(CountryNum,style: TextStyle(color: Colors.black,fontSize: 14.sp),)),
              Icon(Icons.arrow_drop_down,color: MyColors.authTipColor,),
              Text("丨",style: TextStyle(color: MyColors.hintColor,)),
              Container(
                height: 40.h,
                width: 180.w,
                alignment: Alignment.centerLeft,
                child:TextField(
                  style: TextStyle(color: Colors.black),
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                    filled: true,
                    fillColor: Color.fromRGBO(248, 248, 248, 1),

                    hintText: messages["请输入手机号码"],

                    //边框
                    focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Color.fromRGBO(248, 248, 248, 1))),
                    enabledBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color:Color.fromRGBO(248, 248, 248, 1),)),

                    hintStyle: TextStyle(
                      color: Color.fromRGBO(183, 183, 183, 1),
                      fontSize: MyFontSizes.commonrText.sp,
                    ),
                  ),
                  onChanged: (value) {
                    setState(() {
                      phoneNum = value;
                    });
                  },

                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 20.h,),
        CustomButton(
          enabled:phoneNum.length==11?true:false,
          width: screenSize.width-60.w,
          height: 40.h,
          borderRadius: 30,
          text: '获取验证码',
          normalColor: phoneNum.length==11?MyColors.themeColor: MyColors.clickColor,
          pressedColor: Colors.white,
          customOnPressed: () {
            if (isAgree=="1") {
              setState(() {
                _isButtonEnabled =false;
              });
              getApiManager.getData(
                context, // 上下文对象，用于显示提示信息等
                'api/auth/auth/driver/getPhoneValidCode', // 您的API端点
                {"phone":phoneNum,"codeType":"LOGIN"}, // 查询参数，如果没有可以传递null
                    (responseData) async {
                  BrnToast.show(
                    "发送成功",
                    context,
                    duration: BrnDuration.short,
                  );
                  Navigator.push( context, FadeRoute(page:SMSView(
                    phoneNumber: phoneNum, validCodeReqNo: responseData['data']['validCodeReqNo'],)));
                },
              );

            }else{
              showDialog(
                context: context,
                builder: (BuildContext context) {
                  return BrnDialog(
                    titleText: "请阅读并同意用户协议",
                    actionsWidget: [
                      TextButton(
                        onPressed: () {
                          Navigator.pop(context);
                          FocusScope.of(context).unfocus();
                        },
                        child: Text("取消",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                      ),
                      TextButton(
                        onPressed: () {
                          setState(() {
                            isAgree="1";
                            // FocusScope.of(context).unfocus();
                            setState(() {
                              _isButtonEnabled =false;
                            });
                            getApiManager.getData(
                              context, // 上下文对象，用于显示提示信息等
                              'api/auth/auth/driver/getPhoneValidCode', // 您的API端点
                              {"phone":phoneNum,"codeType":"LOGIN"}, // 查询参数，如果没有可以传递null
                                  (responseData) async {
                                BrnToast.show(
                                  "发送成功",
                                  context,
                                  duration: BrnDuration.short,
                                );
                                Navigator.pop(context);
                                Navigator.push( context, FadeRoute(page:SMSView(
                                  phoneNumber: phoneNum, validCodeReqNo: responseData['data']['validCodeReqNo'],)));
                              },
                            );
                          });
                        },
                        child: Text("同意",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                      ),

                    ],
                  );
                },
              );
            }
          },

        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            TextButton(onPressed: (){
              Navigator.push( context, FadeRoute(page:VerifyPhoneUserID()));
            }, child: Text("手机号不用了无法登陆？",style: TextStyle(color: MyColors.authTipColor),)),
            SizedBox(width: 20.w,),
          ],
        ),
        SizedBox(height: 10.h,),
        Container(
          height: 40.h ,
          margin: EdgeInsets.only(left: 30.w,right: 30.w),
          child: MobLogin(),


        ),
        SizedBox(height: 80.h,),
        Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                "lib/Images/login/line.png",
                height: 1.h,
                width:20.w,
              ),
              Text("其他方式登录",style: TextStyle(color: Colors.grey,fontSize: MyFontSizes.smallText.sp,)),
              Image.asset(
                "lib/Images/login/line.png",
                height: 1.h,
                width:20.w,),
            ]
        ),




        SizedBox(height: 10.h,),
        ThirdView(),
        SizedBox(height: 30.h,),
        Container(
          margin: EdgeInsets.only(left: 10, right: 10),
          child: Row(
            children: [
              Column(
                children: [
                  IconButton(
                    onPressed: () => {
                      setState(() {
                        if (isAgree == "1") {
                          isAgree = "0";
                        } else {
                          isAgree = "1";
                        }
                      })
                    },
                    icon:isAgree == "0" ? Icon(Icons.radio_button_unchecked): Icon(Icons.radio_button_checked),
                    color: isAgree == "1" ? Colors.orange : Colors.grey,
                  ),
                  SizedBox(height: 25.h,),
                ],
              ),
              Container(
                width: 290.w,
                child:  RichText(
                  text: TextSpan(children: [

                    TextSpan(
                        text: '已阅读并同意 ',
                        style: TextStyle(fontSize: 12.sp, color: Colors.black54)),
                    TextSpan(
                        text: '《速配货用户协议》',
                        style: TextStyle(fontSize: 12.sp, color: Colors.blue),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            Navigator.push( context, FadeRoute(page:ProtocolDisplay(id: "1760507434822107138",)));
                          }),
                    TextSpan(
                        text: '《速配货隐私政策》',
                        style: TextStyle(fontSize: 12.sp, color: Colors.blue),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            Navigator.push( context, FadeRoute(page:ProtocolDisplay(id: "1805853267043028993",)));
                          }),

                    TextSpan(
                        text: '《第三方合作清单》',
                        style: TextStyle(fontSize: 12.sp, color: Colors.blue),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            Navigator.push( context, FadeRoute(page:ProtocolDisplay(id: "1806571891806515202",)));
                          }),
                    TextSpan(
                        text: ',未注册的手机号将自动完成账号注册',
                        style: TextStyle(fontSize: 12.sp, color: Colors.black54)),
                  ]),
                ),
              ),

            ],
          ),

        ),


      ],
      ),

    );




  }
}


class ThirdView extends StatefulWidget {
  const ThirdView({super.key});

  @override
  State<ThirdView> createState() => _ThirdViewState();
}

class _ThirdViewState extends State<ThirdView> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    ShareSDKRegister register = ShareSDKRegister();
    register.setupWechat(
        "wxa8dde8d9a749a5cf ", "69b3e8632bc94b9dce51cd1b88671f28", "https://app.sph56.cn/");

    register.setupDouyin(
      "awzr6yccp3h73i3w", "6596b1044a8747093c4da8c92b2490ec",);
    register.setupQQ("100371282", "aed9b0303e3ed1e27bae87c33761161d");

    SharesdkPlugin.regist(register);
  }
  /// @param 隐私协议返回数据的格式
  /// POLICY_TYPE_URL = 1
  /// POLICY_TYPE_TXT = 2
  getPrivacyPolicyUrl(BuildContext context) {
    SharesdkPlugin.getPrivacyPolicy("1", "en-CN", (dynamic data, dynamic error) {
      String? policyData, errorStr;
      if (data != null) {
        policyData = data["data"];
        print("==============>policyData " + policyData!);
      }

      if (error != null) {
        errorStr = error["error"];
        print("==============>errorStr " + errorStr!);
      }

      if (policyData != null) {
        print("隐私协议"+ policyData);
      } else if (errorStr != null) {
        print("隐私协议"+ errorStr);
      } else {
        print("隐私协议"+ "获取隐私协议失败:此接口已废弃");
      }
    });
  }
  submitPrivacyGrantResult(BuildContext context) {
    SharesdkPlugin.uploadPrivacyPermissionStatus(1, (bool success) {
      if (success == true) {
        print("隐私协议授权提交结果:"+"成功");
      } else {
        print("隐私协议授权提交结果:"+ "失败");
      }
    });
  }
  @override
  Widget build(BuildContext context) {
    return  Container(
      margin: EdgeInsets.only(left: 10, right: 10),


      child:   Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          GestureDetector(

            child: Image.asset(
              "lib/Images/login/微信登录.png",
              height: 50.h,
              width:40.w,
            ),
            onTap: ()async {
              SharesdkPlugin.getUserInfo(ShareSDKPlatforms.wechatSession,
                      (SSDKResponseState state, dynamic user, SSDKError error) {
                    print(user != null ? user : error.rawData);
                  });
            },
          ),
          SizedBox(
            width: 40.w,
          ),
          GestureDetector(
            child: Image.asset(
              "lib/Images/login/抖音登录.png",
              height: 40.h,
              width: 40.w,
            ),
            onTap: () async{
              SharesdkPlugin.getUserInfo(ShareSDKPlatforms.douyin,
                      (SSDKResponseState state, dynamic user, SSDKError error) {
                    print(user != null ? user : error.rawData);
                  });
            },
          ),

          SizedBox(
            width:Platform.isIOS? 40.w:0,
          ),
          Platform.isIOS?GestureDetector(
            child: Image.asset(
              "lib/Images/login/苹果登录.png",
              height: 40.h,
              width:40.w,
            ),
            onTap: () {
              SharesdkPlugin.getUserInfo(ShareSDKPlatforms.apple,
                      (SSDKResponseState state, dynamic user, SSDKError error) {
                    print(user != null ? user : error.rawData);
                  });

            },
          ):SizedBox(width: 0,),
        ],
      ),
    );







  }
}
